package main

import (
	"flag"
	"github.com/gin-gonic/gin"
	"gopkg.in/ini.v1"
	"log"
	"net/http"
	"scott.lee/git-viewer/git"
)

var Repos map[string]*git.Repository

func main() {
	port := flag.String("p", ":20000", "端口")
	flag.Parse()
	r := gin.Default()
	r.StaticFile("/", "./html/index.html")
	r.StaticFile("/favicon.ico", "./html/favicon.ico")
	r.StaticFile("/manifest.json", "./html/manifest.json")
	r.StaticFS("/static", http.Dir("./html/static"))
	r.GET("/logs/:projectName", gitLogsHandler)
	r.GET("/branches/:projectName", getBranches)
	log.Printf("port: %s", *port)
	log.Fatal(http.ListenAndServe(*port, r))
}

func gitLogsHandler(context *gin.Context) {
	projectName := context.Param("projectName")
	user := context.Query("user")
	since := context.Query("since")
	before := context.Query("before")
	keyword := context.Query("keyword")
	branch := context.Query("branch")
	repository := Repos[projectName]
	result := repository.Logs2(branch, user, before, since, keyword)
	context.JSON(200, result)
}
func getBranches(context *gin.Context) {
	projectName := context.Param("projectName")
	repository := Repos[projectName]
	context.JSON(200, repository.Branches())
}

func init() {
	Repos = make(map[string]*git.Repository)
	load, err := ini.Load("./config.ini")
	if err != nil {
		log.Panic(err)
	}
	sections := load.SectionStrings()
	for _, section := range sections {
		if section == "DEFAULT" {
			continue
		}
		item, _ := load.GetSection(section)
		repoName := item.Name()
		path, _ := item.GetKey("path")
		pathValue := path.String()
		branch, _ := item.GetKey("branch")
		branchValue := branch.String()
		Repos[repoName] = &git.Repository{
			Path:   pathValue,
			Branch: branchValue,
		}
	}
}
